﻿using System.Diagnostics;
using System.IO;
using System.Net;
using System.Net.Sockets;
using System.Runtime.Serialization;
using System.Security.Policy;
using System.Text;
using System.Text.RegularExpressions;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Windows.Threading;
using System.Xml;
using Path = System.IO.Path;

namespace SichuanInspection;

/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
    /// <summary>
    /// 图片列表
    /// </summary>
    private Dictionary<string, string> ImageSourceList = new Dictionary<string, string>();

    /// <summary>
    /// 当前图片列表
    /// </summary>
    private List<Uri> CurrentImageSourceList = new List<Uri>();

    /// <summary>
    /// 当前图片的坐标
    /// </summary>
    private int ImageIndex = 0;

    /// <summary>
    /// 当前key值
    /// </summary>
    private string CurrentKeyVal = "mofanjianchayuan";

    /// <summary>
    /// 配置
    /// </summary>
    private Config SetConfig = new Config();

    /// <summary>
    /// 窗口宽度
    /// </summary>
    private int WindowWidth = 1920;

    /// <summary>
    /// 窗口高度
    /// </summary>
    private int WindowHeight = 1080;

    /// <summary>
    /// 窗口的X轴缩放
    /// </summary>
    private double Window_ScaleX = 1;

    /// <summary>
    /// 窗口的Y轴缩放
    /// </summary>
    private double Window_ScaleY = 1;

    /// <summary>
    /// 窗口左侧距离
    /// </summary>
    private double Window_MarginLeft = 0;

    /// <summary>
    /// 窗口顶部距离
    /// </summary>
    private double Window_MarginTop = 0;

    /// <summary>
    /// 轮播图路径
    /// </summary>
    private string[] imageFIles;

    /// <summary>
    /// 轮播图目前索引
    /// </summary>
    private int SwiperCurrentIndex = 0;

    /// <summary>
    /// 轮播图计时器
    /// </summary>
    private DispatcherTimer timer;

    /// <summary>
    /// 轮播图图片根目录
    /// </summary>
    private string SwiperFolder = "Assets/省检-荣誉界面-轮播";

    /// <summary>
    /// 轮播图切换时间间隔
    /// </summary>
    private int SwiperChangeSecond = 2;

    /// <summary>
    /// 目标端口
    /// </summary>
    private int port = 8888;

    /// <summary>
    /// 目标IP
    /// </summary>
    private string ipAddress = "127.0.0.1";

    /// <summary>
    /// UDP对象
    /// </summary>
    private UdpClient UdpClient;

    /// <summary>
    /// 本地端口号
    /// </summary>
    private int localPort = 8888;
    /// <summary>
    /// 
    /// </summary>
    private bool isListening;

    public MainWindow()
    {
        InitializeComponent();
        ReadOrSetConfig(); 
        if (UdpClient == null)
        {
            UdpClient = new UdpClient(localPort);
        }
        isListening = true;
        Task.Run(() => ListenForUdpMessages());
    }

    /// <summary>
    /// 首页进入目录页点击事件
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    private void HomeBtn_Click(object sender, RoutedEventArgs e)
    {
        Home.IsSelected = false;
        Content.IsSelected = true;
    }

    /// <summary>
    /// 目录页返回按钮
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    private void ContentBtn_Click(object sender, RoutedEventArgs e)
    {
        Home.IsSelected = true;
        Content.IsSelected = false;
    }

    /// <summary>
    /// 下一张点击事件
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    private void Next_Picture_Click(object sender, RoutedEventArgs e)
    {
        if (ImageIndex < CurrentImageSourceList.Count - 1)
        {
            ImageIndex++;
            Detail_Image.ImageSource = new BitmapImage(CurrentImageSourceList[ImageIndex]);
        }
    }

    /// <summary>
    /// 上一张点击事件
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    private void Last_Picture_Click(object sender, RoutedEventArgs e)
    {
        if (ImageIndex > 0)
        {
            ImageIndex--;
            Detail_Image.ImageSource = new BitmapImage(CurrentImageSourceList[ImageIndex]);
        }
    }

    /// <summary>
    /// 目录按钮点击事件
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    private void Content_Btn_Click(object sender, RoutedEventArgs e)
    {
        Button btn = (Button)sender;
        string param = btn.Content.ToString();
        if (param == "suzhibing")
        {
            Video1.IsEnabled = true;
            Video2.IsEnabled = true;
        }

        ImageIndex = 0;
        CurrentImageSourceList = GetUris(ImageSourceList[param]);
        Detail_Image.ImageSource = new BitmapImage(CurrentImageSourceList[ImageIndex]);
        Content.IsSelected = false;
        Detail_Page.IsSelected = true;
    }

    /// <summary>
    /// 切换点击事件
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    private void ChangBtn_Click(object sender, RoutedEventArgs e)
    {
        LoadImage(SwiperFolder);
        SendUdpCommand("lb");
        SetupTimer();
        Content.IsSelected = false;
        Swiper.IsSelected = true;
    }

    /// <summary>
    /// 详情页返回点击事件
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    private void Detail_Page_Back_Click(object sender, RoutedEventArgs e)
    {
        Detail_Page.IsSelected = false;
        Content.IsSelected = true;
        Video1.IsEnabled = false;
        Video2.IsEnabled = false;
    }

    /// <summary>
    /// 读取或者生成配置
    /// </summary>
    private void ReadOrSetConfig()
    {
        if (File.Exists("MZ.xml"))
        {
            using (FileStream fs = new FileStream("MZ.xml", FileMode.Open, FileAccess.Read))
            {
                DataContractSerializer dataContract = new DataContractSerializer(typeof(Config));
                try
                {
                    SetConfig = dataContract.ReadObject(fs) as Config;
                    SetImageSourceList(SetConfig);
                }
                catch (Exception e)
                {
                    Console.WriteLine("ReadInfoFromXmlFuncErrorMessage:" + e.Message);
                }
            }
        }
        //如果不存在就设置和创建配置文件
        else
        {
            SetConfig.Window_Width = 1920;
            SetConfig.Window_Height = 1080;
            SetConfig.Wondow_MarginLeft = 0;
            SetConfig.Wondow_MarginTop = 0;
            SetConfig.Window_ScaleX = 1;
            SetConfig.Window_ScaleY = 1;
            SetConfig.SwiperImageFolder = "Assets\\省检-荣誉界面-轮播";
            SetConfig.SwiperChangeSecond = 2;
            SetConfig.ipAddress = "127.0.0.1";
            SetConfig.port = 8686;
            SetConfig.HomeImagePath = "Assets/Home.JPG";
            SetConfig.loaclPort = 8888;
            //先进集体-全国模范检察院
            SetConfig.Collectives.National_Model_Procuratorate_Picture_List = "Assets\\省检-荣誉界面-点播\\02先进集体\\02-1全国模范检察院";

            //先进集体-全国先进基层
            SetConfig.Collectives.National_Advanced_Party_Picture_List = "Assets\\省检-荣誉界面-点播\\02先进集体\\02-2全国先进基层党组织";

            //先进集体-四川省先进基层
            SetConfig.Collectives.Sichuan_Advanced_Party_Picture_List = "Assets\\省检-荣誉界面-点播\\02先进集体\\02-3四川省先进基层党组织";

            //先进集体-四川省人民满意的公务员
            SetConfig.Collectives.Sichuan_Satisfied_Servant_Picture_List =
                "Assets\\省检-荣誉界面-点播\\02先进集体\\02-4四川省人民满意的公务员集体";

            //先进集体-集体一等功
            SetConfig.Collectives.Collective_First_Class_Merit_Picture_List = "Assets\\省检-荣誉界面-点播\\02先进集体\\02-5集体一等功";

            //先进集体-其他省部级表彰
            SetConfig.Collectives.Other_Provincial_Picture_List = "Assets\\省检-荣誉界面-点播\\02先进集体\\02-6其他省部级表彰";

            //先进个人-四川省人民满意的公务员
            SetConfig.Individual.Sichuan_Satisfied_Servant_Picture_List =
                "Assets\\省检-荣誉界面-点播\\03先进个人\\03-10四川省人民满意的公务员";
            //先进个人-四川省维护藏区稳定模范
            SetConfig.Individual.Sichuan_Maintaining_Stability_Picture_List =
                "Assets\\省检-荣誉界面-点播\\03先进个人\\03-11四川省维护藏区稳定模范";
            //先进个人-个人一等功
            SetConfig.Individual.Personal_First_Class_Merit_Picture_List = "Assets\\省检-荣誉界面-点播\\03先进个人\\03-12个人一等功";
            //先进个人-其他省部级表彰
            SetConfig.Individual.Other_Provincial_Picture_List = "Assets\\省检-荣誉界面-点播\\03先进个人\\03-13其他省部级表彰";
            //先进个人-全国先进工作者
            SetConfig.Individual.Advanced_Workers_Picture_List = "Assets\\省检-荣誉界面-点播\\03先进个人\\03-1全国先进工作者";
            //先进个人-全国人民满意的公务员
            SetConfig.Individual.Satisfied_Servant_Picture_List = "Assets\\省检-荣誉界面-点播\\03先进个人\\03-2全国人民满意的公务员";
            //先进个人-全国模范检察官
            SetConfig.Individual.National_Model_Prosecutor_Picture_List = "Assets\\省检-荣誉界面-点播\\03先进个人\\03-3全国模范检察官";
            //先进个人-全国模范检察干部
            SetConfig.Individual.National_Model_Procuratorial_Cadre_Picture_List =
                "Assets\\省检-荣誉界面-点播\\03先进个人\\03-4全国模范检察干部";
            //先进个人-全国模范退役军人
            SetConfig.Individual.Retired_Soldiers_Member_Picture_List = "Assets\\省检-荣誉界面-点播\\03先进个人\\03-5全国模范退役军人";
            //先进个人-四川省优秀共产党员
            SetConfig.Individual.Outstanding_Communist_Party_Member_Picture_List =
                "Assets\\省检-荣誉界面-点播\\03先进个人\\03-6四川省优秀共产党员";
            //先进个人-四川省先进工作者
            SetConfig.Individual.Sichuan_Advanced_Workers_Picture_List = "Assets\\省检-荣誉界面-点播\\03先进个人\\03-7四川省先进工作者";
            //先进个人-四川省劳动模范
            SetConfig.Individual.Sichuan_Model_Worker_Picture_List = "Assets\\省检-荣誉界面-点播\\03先进个人\\03-8四川省劳动模范";
            //先进个人-抗震救灾
            SetConfig.Individual.Earthquake_Relief_Picture_List = "Assets\\省检-荣誉界面-点播\\03先进个人\\03-9抗震救灾模范";

            //业务专家与荣誉-全国检察业务专家
            SetConfig.Experts_Honors.Business_Specialists_Picture_List = "Assets\\省检-荣誉界面-点播\\04业务专家与荣誉\\04-1全国检察业务专家";
            //业务专家与荣誉-全国十佳
            SetConfig.Experts_Honors.Top_Ten_Picture_List = "Assets\\省检-荣誉界面-点播\\04业务专家与荣誉\\04-2全国十佳";
            //业务专家与荣誉-全国检察机关业务标兵
            SetConfig.Experts_Honors.Business_Pacesetter_Picture_List = "Assets\\省检-荣誉界面-点播\\04业务专家与荣誉\\04-3全国检察机关业务标兵";

            //检察英模代表
            SetConfig.HeroicModel.Suzhibin_Picture_Path = "Assets\\省检-荣誉界面-点播\\01检察英模代表\\苏知斌";
            SetConfig.HeroicModel.Renjiancao_Picture_Path = "Assets\\省检-荣誉界面-点播\\01检察英模代表\\任建操";
            SetConfig.HeroicModel.Chenjun_Picture_Path = "Assets\\省检-荣誉界面-点播\\01检察英模代表\\陈军";
            SetImageSourceList(SetConfig);
            DataContractSerializer setConfigData = new DataContractSerializer(typeof(Config));
            XmlWriterSettings writerSettings = new XmlWriterSettings { Indent = true };
            using (XmlWriter xmlWriter = XmlWriter.Create("MZ.xml", writerSettings))
            {
                setConfigData.WriteObject(xmlWriter, SetConfig);
            }
        }
    }

    //设置默认的图片列表
    private void SetImageSourceList(Config config)
    {
        // 检查 ImageSourceList 是否已初始化
        if (ImageSourceList == null)
        {
            ImageSourceList = new Dictionary<string, string>();
        }

        Width = config.Window_Width;
        Height = config.Window_Height;
        Window_Scale.ScaleX = config.Window_ScaleX;
        Window_Scale.ScaleY = config.Window_ScaleY;
        Top = config.Wondow_MarginTop;
        Left = config.Wondow_MarginLeft;
        SwiperChangeSecond = config.SwiperChangeSecond;
        SwiperFolder = config.SwiperImageFolder;
        port = config.port;
        ipAddress = config.ipAddress;
        string allPath = Path.Combine(AppContext.BaseDirectory, config.HomeImagePath);
        HomeImage.ImageSource = new BitmapImage(new Uri(allPath, UriKind.RelativeOrAbsolute));
        localPort = config.loaclPort;
        // 先进集体
        ImageSourceList["mofanjianchayuan"] = config.Collectives.National_Model_Procuratorate_Picture_List;
        ImageSourceList["xianjinjicengdhzuzhi"] = config.Collectives.National_Advanced_Party_Picture_List;
        ImageSourceList["sc_xianjinjicengdangzuzhi"] = config.Collectives.Sichuan_Advanced_Party_Picture_List;
        ImageSourceList["gongwujiti"] = config.Collectives.Sichuan_Satisfied_Servant_Picture_List;
        ImageSourceList["jitiyidenggong"] = config.Collectives.Collective_First_Class_Merit_Picture_List;
        ImageSourceList["qitashengbubiaozhang"] = config.Collectives.Other_Provincial_Picture_List;
        // 先进个人
        ImageSourceList["xianjingongzuozhe"] = config.Individual.Advanced_Workers_Picture_List;
        ImageSourceList["manyidegongwuyuan"] = config.Individual.Satisfied_Servant_Picture_List;
        ImageSourceList["mofanjianchaguan"] = config.Individual.National_Model_Prosecutor_Picture_List;
        ImageSourceList["mofanjianchaganbu"] = config.Individual.National_Model_Procuratorial_Cadre_Picture_List;
        ImageSourceList["mofantuiyijunren"] = config.Individual.Retired_Soldiers_Member_Picture_List;
        ImageSourceList["youxiugongchandangyuan"] = config.Individual.Outstanding_Communist_Party_Member_Picture_List;
        ImageSourceList["sc_xianjingongzuozhe"] = config.Individual.Sichuan_Advanced_Workers_Picture_List;
        ImageSourceList["sc_laodongmofan"] = config.Individual.Sichuan_Model_Worker_Picture_List;
        ImageSourceList["kangzhenjiuzaimofan"] = config.Individual.Earthquake_Relief_Picture_List;
        ImageSourceList["sc_manyidegongwuyuan"] = config.Individual.Sichuan_Satisfied_Servant_Picture_List;
        ImageSourceList["sc_weihuzangquwendingmofan"] = config.Individual.Sichuan_Maintaining_Stability_Picture_List;
        ImageSourceList["gerenyidenggong"] = config.Individual.Personal_First_Class_Merit_Picture_List;
        ImageSourceList["gr_qitashengbubiaozhang"] = config.Individual.Other_Provincial_Picture_List;
        // 检察业务专家与竞赛荣誉
        ImageSourceList["quanguoshijia"] = config.Experts_Honors.Top_Ten_Picture_List;
        ImageSourceList["yewuzhuanjia"] = config.Experts_Honors.Business_Specialists_Picture_List;
        ImageSourceList["jiguanyewubiaobing"] = config.Experts_Honors.Business_Pacesetter_Picture_List;
        // 检察英模代表
        ImageSourceList["renjiancao"] = config.HeroicModel.Renjiancao_Picture_Path;
        ImageSourceList["chengjun"] = config.HeroicModel.Chenjun_Picture_Path;
        ImageSourceList["suzhibing"] = config.HeroicModel.Suzhibin_Picture_Path;
    }

    /// <summary>
    /// 获取图片的Uri对象列表
    /// </summary>
    /// <param name="paths"></param>
    /// <returns></returns>
    private List<Uri> GetUris(string paths)
    {
        List<Uri> uris = new List<Uri>();
        if (string.IsNullOrWhiteSpace(paths))
        {
            MessageBox.Show("路径不能为空！");
            Application.Current.Shutdown(); // 关闭应用程序
            return uris;
        }

        try
        {
            string folderPath = Path.Combine(AppContext.BaseDirectory, paths);
            string[] currentImagePathList = Directory.GetFiles(folderPath, "*.jpg")
                .OrderBy(f => ExtractNumber(Path.GetFileNameWithoutExtension(f)))
                .ToArray();
            foreach (var path in currentImagePathList)
            {
                // 尝试创建 Uri 对象
                try
                {
                    string ImagePath = Path.Combine(AppContext.BaseDirectory, path);
                    Uri uri = new Uri(ImagePath, UriKind.RelativeOrAbsolute);
                    uris.Add(uri);
                }
                catch (UriFormatException uriEx)
                {
                    MessageBox.Show($"Invalid URL: {path}\n{uriEx.Message}");
                    Application.Current.Shutdown(); // 关闭应用程序
                    break;
                }
            }
        }
        catch (Exception ex)
        {
            MessageBox.Show($"Error: {ex.Message}");
            Application.Current.Shutdown(); // 关闭应用程序
        }

        return uris;
    }

    /// <summary>
    /// 轮播图暂停点击事件
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    private void PauseBtn_OnClick(object sender, RoutedEventArgs e)
    {
        if (timer.IsEnabled)
        {
            timer.Stop();
            SendUdpCommand("zt");
        }
        else
        {
            SendUdpCommand("bf");
            timer.Start();
        }
    }


    /// <summary>
    /// 加载轮播图片
    /// </summary>
    /// <returns></returns>
    private void LoadImage(string folderPath)
    {
        if (string.IsNullOrWhiteSpace(folderPath) || !Directory.Exists(folderPath))
        {
            Console.WriteLine("Invalid folder path.");
            return;
        }

        imageFIles = Directory.GetFiles(folderPath, "*.jpg")
            .OrderBy(f => ExtractNumber(Path.GetFileNameWithoutExtension(f))).ToArray();
        if (imageFIles.Length > 0)
        {
            SwiperCurrentIndex = 0; // 确保从第一张图片开始
            DisplayImage(imageFIles[SwiperCurrentIndex]);
        }
        else
        {
            string rootPath = AppDomain.CurrentDomain.BaseDirectory;
            string imagesPath = Path.Combine(rootPath, folderPath);
            MessageBox.Show($"没有找到图片：{imagesPath}");
        }
    }

    /// <summary>
    /// 提取文件名中的第一个数字用于排序
    /// </summary>
    /// <param name="fileName">文件名</param>
    /// <returns></returns>
    private int ExtractNumber(string fileName)
    {
        var match = Regex.Match(fileName, @"\d+");
        return match.Success ? int.Parse(match.Value) : int.MaxValue; // 无数字的文件名排在最后
    }

    /// <summary>
    /// 展示图片
    /// </summary>
    /// <param name="ImagePath">图片路径</param>
    private void DisplayImage(string ImagePath)
    {
        BitmapImage swiperImageSource = new BitmapImage();
        swiperImageSource.BeginInit();
        swiperImageSource.UriSource = new Uri(ImagePath, UriKind.RelativeOrAbsolute);
        swiperImageSource.CacheOption = BitmapCacheOption.OnLoad; // 确保图片在加载时就完全解码
        swiperImageSource.EndInit();
        SwiperImage.ImageSource = swiperImageSource;
    }

    /// <summary>
    /// 设置定时器
    /// </summary>
    private void SetupTimer()
    {
        //设置定时器
        timer = new DispatcherTimer();
        timer.Interval = TimeSpan.FromSeconds(SwiperChangeSecond);
        timer.Tick += Timer_Tick;
        timer.Start();
    }

    /// <summary>
    /// 定时器每次滴答时调用的方法，用于切换图片显示
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    private void Timer_Tick(object? sender, EventArgs e)
    {
        if (imageFIles.Length == 0)
        {
            return; // 如果没有图片，直接返回
        }

        SwiperCurrentIndex = (SwiperCurrentIndex + 1) % imageFIles.Length;
        DisplayImage(imageFIles[SwiperCurrentIndex]);
    }

    /// <summary>
    /// 点击按钮时停止定时器，发送UDP指令并切换页面
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    private void SwiperBtn_Click(object sender, RoutedEventArgs e)
    {
        if (timer != null)
        {
            timer.Stop(); // 停止定时器
            timer.Tick -= Timer_Tick; // 解除事件处理程序的绑定
            timer = null; // 解除对定时器的引用
        }

        SendUdpCommand("fh");
        Swiper.IsSelected = false;
        Content.IsSelected = true;
    }

    /// <summary>
    /// 键盘事件处理方法，用于调整窗口位置并保存配置
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    private void Window_KeyDown(object sender, KeyEventArgs e)
    {
        if (Keyboard.IsKeyDown(Key.LeftCtrl) && Keyboard.IsKeyDown(Key.Up))
        {
            this.Top -= 1;
            SetConfig.Wondow_MarginTop = Convert.ToInt32(this.Top);
        }
        else if (Keyboard.IsKeyDown(Key.LeftCtrl) && Keyboard.IsKeyDown(Key.Down))
        {
            this.Top += 1;
            SetConfig.Wondow_MarginTop = Convert.ToInt32(this.Top);
        }
        else if (Keyboard.IsKeyDown(Key.LeftCtrl) && Keyboard.IsKeyDown(Key.Left))
        {
            this.Left -= 1;
            SetConfig.Wondow_MarginLeft = Convert.ToInt32(this.Left);
        }
        else if (Keyboard.IsKeyDown(Key.LeftCtrl) && Keyboard.IsKeyDown(Key.Right))
        {
            this.Left += 1;
            SetConfig.Wondow_MarginLeft = Convert.ToInt32(this.Left);
        }
        else if (Keyboard.IsKeyDown(Key.LeftCtrl) && Keyboard.IsKeyDown(Key.S))
        {
            // 创建序列化器
            DataContractSerializer SetConfigData = new DataContractSerializer(typeof(Config));
            // 声明XMLWriterSettings对象
            XmlWriterSettings Settings = new XmlWriterSettings { Indent = true };
            using (XmlWriter XW = XmlWriter.Create("MZ.xml", Settings))
            {
                // 将数据写入XML
                SetConfigData.WriteObject(XW, SetConfig);
            }
        }
    }

    /// <summary>
    /// 视频按钮点击事件处理方法，播放视频并切换页面
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    private void Video_Btn_Click(object sender, RoutedEventArgs e)
    {
        mediaElement.Opacity = 0;
        Button btn = (Button)sender;
        string param = btn.Content.ToString();
        string allPath = Path.Combine(AppContext.BaseDirectory, SetConfig.HeroicModel.Suzhibin_Picture_Path);
        string videoPath = allPath + param;
        if (string.IsNullOrEmpty(videoPath))
        {
            MessageBox.Show("Please enter a video path.");
            return;
        }

        try
        {
            mediaElement.Source = new Uri(videoPath, UriKind.RelativeOrAbsolute);
            mediaElement.LoadedBehavior = MediaState.Manual;
            mediaElement.UnloadedBehavior = MediaState.Stop;

            mediaElement.MediaFailed += MediaElement_MediaFailed;
            mediaElement.MediaOpened += MediaElementOnMediaOpened;
            mediaElement.Play();
        }
        catch (Exception ex)
        {
            MessageBox.Show("Error loading video: " + ex.Message);
        }

        Detail_Page.IsSelected = false;
        Video_Page.IsSelected = true;
    }

    /// <summary>
    /// 视频打开成功时调用的方法，设置MediaElement的透明度
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    private void MediaElementOnMediaOpened(object sender, RoutedEventArgs e)
    {
        mediaElement.Opacity = 1;
    }

    /// <summary>
    /// 视频播放结束时调用的方法，切换回详细信息页面
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    private void mediaElement_MediaEnded(object sender, RoutedEventArgs e)
    {
        Video_Page.IsSelected = false;
        Detail_Page.IsSelected = true;
    }

    /// <summary>
    /// 视频返回按钮点击事件处理方法，停止视频播放并切换回详细信息页面
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    private void Video_Back_Btn_Click(object sender, RoutedEventArgs e)
    {
        mediaElement.Stop();
        Video_Page.IsSelected = false;
        Detail_Page.IsSelected = true;
    }

    /// <summary>
    /// 视频加载失败时调用的方法，显示错误消息
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    private void MediaElement_MediaFailed(object sender, ExceptionRoutedEventArgs e)
    {
        MessageBox.Show("Media failed to load: " + e.ErrorException.Message);
    }

    /// <summary>
    /// 异步监听UDP消息的方法
    /// </summary>
    private async Task ListenForUdpMessages()
    {
        try
        {
            while (isListening)
            {
                UdpReceiveResult result = await UdpClient.ReceiveAsync();
                string message = Encoding.UTF8.GetString(result.Buffer);
                Debug.WriteLine("message: " + message);
            }
        }
        catch (Exception e)
        {
            Dispatcher.Invoke(() =>
            {
                //MessageBox.Show("Error: " + e.Message);
            });
        }
    }

    /// <summary>
    /// 发送UDP指令的方法
    /// </summary>
    private void SendUdpCommand(string command)
    {
        using (UdpClient udpClient = new UdpClient())
        {
            try
            {
                byte[] sendBytes = Encoding.UTF8.GetBytes(command);
                udpClient.Send(sendBytes, sendBytes.Length, ipAddress, port);
            }
            catch (Exception ex)
            {
                Debug.WriteLine("Error: " + ex.Message);
                Application.Current.Shutdown(); // 关闭应用程序
            }
        }
    }

    /// <summary>
    /// 窗口关闭事件处理方法，关闭UDP客户端
    /// </summary>
    /// <param name="e"></param>
    protected override void OnClosing(System.ComponentModel.CancelEventArgs e)
    {
        isListening = false;
        UdpClient?.Close();
        base.OnClosing(e);
    }
}